package com.jz.netthings.security.browser.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jz.netthings.bean.AdscmLogEntity;
import com.jz.netthings.bean.system.JyUser;
import com.jz.netthings.core.dao.mysql.AdscmLogMapper;
import com.jz.netthings.security.support.SimpleResponse;
import com.jz.netthings.security.utils.AdscmSecurityUtils;
import com.jz.netthings.security.utils.Token;
import com.jz.netthings.utils.AdscmBaseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * @author yyy
 * @ClassName AdscmAuthenticationSuccessHandler
 * @Description 登录成功处理逻辑
 * @date 2018/7/26 15:38
 */
@Component
public class AdscmFormAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    RedisTemplate<Object,Token> tokenRedisTemplate;
    @Autowired
    AdscmLogMapper adscmLogMapper;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        logger.info("登录成功...");

        Token token = setToken(httpServletRequest,authentication);


        httpServletResponse.setContentType("application/json;charset=UTF-8");
        String type = authentication.getClass().getSimpleName();
        httpServletResponse.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse("200","登录成功",token)));



    }

    private Token setToken(HttpServletRequest httpServletRequest, Authentication authentication){

        JyUser user = (JyUser)authentication.getPrincipal();
        String username = user.getUsername();
        String ip = AdscmBaseUtils.getInstance().getIPAddress(httpServletRequest);
        Token token = new Token(user,new Date(),ip);

        //设置token到Redis中
        AdscmSecurityUtils.getInstance().setToken(username,token,tokenRedisTemplate);

        //写给客户端的，没有可以访问的所有url，只有能看到的菜单
        user.setMenus(null);
        try {
            logger.info("写登录日志...");
            AdscmSecurityUtils.getInstance().writeLoginLog(user,ip,"系统登录",username+" ; "+httpServletRequest.getParameter("password"),this.getClass().getName()+".onAuthenticationSuccess","成功",null,adscmLogMapper);
        }catch (Exception e){
            logger.error("写登录日志异常...",e);
        }

        return token;
    }



}
